package com.example.transmit;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

public class Main {
    public static void main(String[] args) {
        TransmittableThreadLocal<Long> clocks = new TransmittableThreadLocal<>();
        Executor executor = taskExecutor();
        for (int i = 0; i < 1000; i++) {
            // 异步执行，使用stream方式接收数据
            StopWatch.remove();
            StopWatch.start();
//            clocks.set(TimeUtil.nowMilliSecond());
            executor.execute(TtlRunnable.get(() -> {
                try {
                    Thread.sleep(new Random().nextInt(100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                StopWatch.stop();
                System.out.println(StopWatch.getTotalTimeMillis());
//                StopWatch.remove();
//                Long aLong = TimeUtil.nowMilliSecond();
//                System.out.println(aLong-clocks.get());
//                clocks.remove();
            }));
        }
        System.out.println();
    }

    public static Executor taskExecutor() {
        int cpuSize = Runtime.getRuntime().availableProcessors();

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(cpuSize > 0 ? cpuSize : 3);
        // 配置最大线程数
        executor.setMaxPoolSize(cpuSize > 0 ? cpuSize * 2 : 6);
        // 配置队列大小
        executor.setQueueCapacity(1000);
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(0);
        // 非守护线程
        executor.setDaemon(false);
        // 配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("trs-server-common-pool-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 异步MDC
        executor.setTaskDecorator(new MdcTaskDecoratorUtil());
        // 执行初始化
        executor.initialize();
        return executor;
    }
}
